package net.janeluo.framework.utils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 获取全局唯一票据服务类
 * 
 * @author yangyining@janeluo.net
 * @date 2014-07-22
 */
public class AccessTokenUtil {
    private static final Log log = Logs.getLog(AccessTokenUtil.class);
    
    private static String AccessToken = "";
    
    private static long time ;
    
    private AccessTokenUtil(){}
    
    /**
     * 获取全局唯一票据
     * 
     * @param request
     * @return 全局唯一票据
     * @throws URISyntaxException 
     * @throws IOException 
     * @throws ClientProtocolException 
     */
    public static String getAccessToken(){
        log.debug("-------------------- 获取全局唯一票据处理开始 ----------------------");
        long nowtime = System.currentTimeMillis() / 1000;
        if (nowtime - time >= 7200) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("grant_type", "client_credential");
            map.put("appid", "wxa9be65b2a6b8a70f");
            map.put("secret", "a8b9cdee8f8da70a98a9830580ddc39b");
            time = nowtime;
            try {
                String string = HttpClientUtils.simpleGetInvoke("https://api.weixin.qq.com/cgi-bin/token", map);
                Map<String, String> jsonmap = new Gson().fromJson(string, new TypeToken<Map<String, String>>() {}.getType());
                
                AccessToken = jsonmap.get("access_token");
                log.debug("AccessToken:" + AccessToken);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
//                e.printStackTrace();
                log.error("获取唯一票据异常！", e);
            } catch (IOException e) {
                // TODO Auto-generated catch block
//                e.printStackTrace();
                log.error("获取唯一票据异常！", e);
            } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
//                e.printStackTrace();
                log.error("获取唯一票据异常！", e);
            }
        }
        
        log.debug("-------------------- 获取全局唯一票据处理结束 ----------------------");
        return AccessToken;
    }
    
    public static void main(String[] args) {
        System.out.println(AccessTokenUtil.getAccessToken());
        System.out.println(AccessTokenUtil.getAccessToken());
    }
    
}

